import { Button, Card, Space } from "antd";
import { min_app_fs, min_app_shell } from '@linksaas-minapp/api';
import { useState } from "react";
import SelectParamModal from "@/components/SelectParamModal";
import useForceUpdate from 'use-force-update';
import { ConfigDefList } from "@/components/config";
import EditParam from "@/components/EditParam";
import toml from "@iarna/toml";

export default function Home() {
  const forceUpdate = useForceUpdate();

  const [clippyCfg, setClippyCfg] = useState<Map<string, unknown>>(new Map());
  const [showModal, setShowModal] = useState(false);

  const openFile = async () => {
    let files = await min_app_fs.readFile(
      false,
      "toml文件", ["toml"]
    );
    if (files.length == 0) {
      return;
    }
    try {
      const content = new TextDecoder("utf-8").decode(files[0].file_data);
      const cfg = toml.parse(content);
      setClippyCfg(new Map(Object.entries(cfg)));
      forceUpdate();
    } catch (e) {
      console.log(e);
    }

  };

  const saveFile = async () => {
    const cfg = Object.fromEntries(clippyCfg.entries());
    const content = toml.stringify(cfg as unknown as toml.JsonMap);
    const data = new TextEncoder().encode(content);
    await min_app_fs.writeFile("clippy.toml", data);
  };

  return (
    <Card title="clippy配置" bordered={false} extra={
      <Space>
        <Button type="link" onClick={e => {
          e.stopPropagation();
          e.preventDefault();
          min_app_shell.openBrowser("https://doc.rust-lang.org/clippy/");
        }}>官方网站</Button>
        <Button onClick={e => {
          e.stopPropagation();
          e.preventDefault();
          setClippyCfg(new Map());
          forceUpdate();
        }}>清空配置</Button>
        <Button onClick={e => {
          e.stopPropagation();
          e.preventDefault();
          openFile();
        }}>导入</Button>
        <Button onClick={e => {
          e.stopPropagation();
          e.preventDefault();
          saveFile();
        }}>导出</Button>
      </Space>
    }>
      <Card title="属性列表" bordered={false} extra={
        <Button onClick={e => {
          e.stopPropagation();
          e.preventDefault();
          setShowModal(true);
        }}>增加属性</Button>
      }>
        {ConfigDefList.filter(item => clippyCfg.has(item.id)).map(cfgDef => (
          <EditParam key={cfgDef.id} cfgDef={cfgDef} value={clippyCfg.get(cfgDef.id)}
            onChange={newValue => {
              setClippyCfg(oldValue => {
                oldValue.set(cfgDef.id, newValue);
                return oldValue;
              });
              forceUpdate();
            }}
            onRemove={() => {
              setClippyCfg(oldValue => {
                oldValue.delete(cfgDef.id);
                return oldValue;
              });
              forceUpdate();
            }} />
        ))}
      </Card>
      {showModal == true && (
        <SelectParamModal paramIdList={Array.from(clippyCfg.keys())} onCancel={() => setShowModal(false)}
          onSelect={(paramId, paramValue) => {
            setClippyCfg(oldValue => {
              oldValue.set(paramId, paramValue);
              return oldValue;
            });
            setShowModal(false);
            forceUpdate();
          }} />
      )}
    </Card>
  )
}
